<template>
  <div class="copy-box">
    <span
      class="copy-box__btn"
      @click.stop="copy()"
    >
      {{ placeholder }}
    </span>
    <textarea
      id="copy_area"
      ref="textCopy"
      v-model="value"
      class="textarea"
    />
  </div>
</template>
<script lang="ts">
import { defineComponent, ref, toRaw, unref } from 'vue'
import { ElMessage } from 'element-plus'
export default defineComponent({
  props: {
    text: {
      type: String,
      default: ''
    },
    placeholder: {
      type: String,
      default: '复制'
    }
  },
  setup(props) {
    const value = ref('')
    const textCopy = ref<any>(null)
    value.value = toRaw(props.text)
    function copy() {
      (unref(textCopy) as HTMLInputElement).select()
      const copy = document.execCommand('copy')
      if (copy) {
        ElMessage({
          message: '复制成功',
          type: 'success'
        })
      }
    }
    return {
      value,
      textCopy,
      copy
    }
  }
})
</script>
<style lang="less" scoped>
.copy-box {
  display: inline-block;
  &__btn {
    cursor: pointer;
    font-size: 12px;
    background-color: #ecf5ff;
    border-color: #d9ecff;
    border-radius: 4px;
    padding: 2px 4px;
    color: #409EFF;
  }
}
.textarea {
  position: absolute;
  top: 0;
  left: 0;
  opacity: 0;
  z-index: -10;
  // transform: translate(100vw);
  // display: none;
}
</style>
